package cn.net.isir.service2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.ResultObject;
import cn.net.isir.common.WxAccessTokenManager;
import cn.net.isir.common.WxErrCode;
import cn.net.isir.utils.HttpUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

/**
 * @author liuxubo
 * @filename SendTemplateMessageService.java
 * @package cn.net.isir.service2
 * @email lxb@isir.net.cn
 * @date 2019/01/02
 * @comment 发送模板消息
 * @since 1.8
 */
@Service
public class SendTemplateMessageService {
    //声明日志对象
    private static Logger logger = Logger.getLogger(SendTemplateMessageService.class);

    /**
     * 微信发送模板消息
     *
     * @param openid      openid
     * @param template_id 模板id
     * @param form_id     表单id
     * @param data        数据
     * @return 结果:200表示成功,500表示失败
     */
    public ResultObject sendWxTemplateMessageService(String openid,
                                                     String template_id,
                                                     String form_id,
                                                     JSONObject data) {

        //添加参数
        JSONObject _message = new JSONObject();
        _message.put("touser", openid);
        _message.put("template_id", template_id);
//        _message.put("page", "pages/index/index");
        _message.put("form_id", form_id);
        _message.put("data", data);

        logger.info(_message.toJSONString());

        String result = HttpUtils.jsonPost(
                "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" +
                        WxAccessTokenManager.getAccessToken(), _message);

        JSONObject jsonObject = JSON.parseObject(result);
        String errcode = String.valueOf(jsonObject.get("errcode"));
        if ("0".equals(errcode)) {
            return new ResultObject(200, "success", jsonObject);
        }
        return new ResultObject(500, WxErrCode.getUnionidErr(errcode), errcode);
    }
}
